<?php declare(strict_types=1);

namespace Zyucv7\Core\Web\Request;

class Header {

    /**
     * 请求头信息
     * 
     * @var array
     */
    private $headers = [];


    /**
     * 服务器变量
     * 
     * @var array
     */
    private $server = [];

    public function __construct(array $server)
    {
        $this->server = $server;
        $this->headers = $this->parseHeaders();
    }

    /**
     * 解析HTTP头信息
     * 
     * @return array
     */
    private function parseHeaders(): array
    {
        $headers = [];
        
        // Apache和其他服务器
        foreach ($this->server as $key => $value) {
            if (strpos($key, 'HTTP_') === 0) {
                $headerName = str_replace('_', '-', substr($key, 5));
                $headers[$headerName] = $value;
            }
        }
        
        // CONTENT_TYPE 和 CONTENT_LENGTH
        if (isset($this->server['CONTENT_TYPE'])) {
            $headers['Content-Type'] = $this->server['CONTENT_TYPE'];
        }
        if (isset($this->server['CONTENT_LENGTH'])) {
            $headers['Content-Length'] = $this->server['CONTENT_LENGTH'];
        }
        
        // 标准化头名称（首字母大写）
        $normalizedHeaders = [];
        foreach ($headers as $name => $value) {
            $normalizedHeaders[$this->normalizeHeaderName($name)] = $value;
        }
        
        return $normalizedHeaders;
    }
    
    /**
     * 获取请求头
     * 
     * @param string|null $name 头名称
     * @param mixed $default 默认值
     * @return mixed
     */
    public function get(string $name, $default = null)
    {
        
        $name = $this->normalizeHeaderName($name);
        return $this->headers[$name] ?? $default;
    }
    
    /**
     * 标准化HTTP头名称
     * 
     * @param string $name
     * @return string
     */
    private function normalizeHeaderName(string $name): string
    {
        return implode('-', array_map('ucfirst', explode('-', strtolower($name))));
    }

    /**
     * 获取所有请求头
     * 
     * @return array
     */
    public function all(): array
    {
        return $this->headers;
    }
    
    /**
     * 获取Content-Type头
     * 
     * @return string
     */
    public function getContentType(): string
    {
        return $this->get('Content-Type', '');
    }

    /**
     * 检查是否为AJAX请求
     * 
     * @return bool
     */
    public function isAjax(): bool
    {
        return strtolower($this->get('X-Requested-With', '')) === 'xmlhttprequest';
    }

    /**
     * 检查是否为JSON请求
     * 
     * @return bool
     */
    public function isJson(): bool
    {
        $contentType = $this->getContentType();
        return strpos($contentType, 'application/json') !== false;
    }

    /**
     * 获取用户代理
     * 
     * @return string
     */
    public function getUserAgent(): string
    {
        return $this->get('User-Agent', '');
    }
    
    /**
     * 获取引用页面
     * 
     * @return string
     */
    public function getReferer(): string
    {
        return $this->get('Referer', '');
    }
}
?>